import ScrollBarLayout from '@/components/ScrollBarLayout';
import { AutoComplete, Card, Empty, Input, Spin, Tree } from 'antd';
import type { TreeProps } from 'antd/es/tree';
import React, { useMemo, useEffect } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { getLoadMapList, getTenantID, loopArray } from '@/utils';
import { useDictionary } from '../common/useDictionary';
import pageStyles from '@/common/pageLayout.less';
import { ILoadMapTypeAll } from '@/common';
interface UpdateNeedMaterialModalLeftAPI {
  prefixCls: string;
  onSelect: (key: string | null) => void;
  onTreeKey: Record<string, any>;
  leftTreeSeatchObj: Record<string, any>;
}

export const UpdateNeedMaterialModalLeft: React.FC<UpdateNeedMaterialModalLeftAPI> = ({
  prefixCls,
  onSelect,
  onTreeKey: { selectKeys, setSelectKeys },
  leftTreeSeatchObj: { typeTreeSearchObj, setTypeTreeSearchObj },
}) => {
  /**
   * 字典获取 - 物料八大类
   * */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`];
  const { loadMapInfo: dictionaryData, mapLoading } = getLoadMapList(loadMdicIds);
  const materialTypeMapList = dictionaryData?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`];

  /**
   * tree组件选中事件
   * */
  const onSelectTree: TreeProps['onSelect'] = (selectedKeys) => {
    if (selectedKeys?.length) {
      setSelectKeys(selectedKeys);
      onSelect(selectedKeys?.toString());
    } else {
      onSelect(null);
      setSelectKeys(selectedKeys);
    }
  };

  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {};

  /**
   * 搜索框的事件
   * */
  const onInputChange = (ev: Record<string, any>) => {
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      searchValue: ev?.target?.value,
    });
  };

  /**
   * 自动完成组件options
   * */
  const autoCompleteOptions = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        const name = item?.name;
        if (name?.includes(typeTreeSearchObj?.searchValue)) {
          const nameLength = name?.length;
          const select = name?.search(typeTreeSearchObj?.searchValue);
          const searchLength = typeTreeSearchObj?.searchValue?.length;
          const afterStr = name?.slice(0, select);
          const selectStr = typeTreeSearchObj?.searchValue;
          const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.id,
            label: (
              <div>
                <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span>
              </div>
            ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(materialTypeMapList);
    return option;
  }, [materialTypeMapList, typeTreeSearchObj?.searchValue]);

  /**
   * 自动完成组件的事件
   * */
  const onAutoSelectLeft = (value: string, option: any) => {
    const optionId = option?.key;
    const targetNode = loopArray(materialTypeMapList)?.find((i) => i?.id == optionId);

    const searchObj: Record<string, any> = {
      searchValue: value,
      // autoExpandParent: true,
      expandedKeys: [targetNode?.pID],
    };

    setTypeTreeSearchObj(searchObj);
    setSelectKeys([optionId]);

    // 向外抛出
    // setSelectKeys(optionId)
    onSelect(optionId);
  };

  /**
   * 树展开方法
   * */
  const onTreeExpand = (e: any) => {
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      expandedKeys: e,
      // autoExpandParent: false
    });
  };

  /**
   * 处理树数据
   * */
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(typeTreeSearchObj?.searchValue);
      const searchLength = typeTreeSearchObj?.searchValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = typeTreeSearchObj?.searchValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                paddingRight: 20,
              }}
              id={item?.id}
            >
              {titleTree}
            </div>
          ),
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
          // disabled: !item?.pID,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              paddingRight: 20,
            }}
            id={item?.id}
          >
            {titleTree}
          </div>
        ),
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  return (
    <Card
      className={prefixCls + 'oneModalBox-leftcard'}
      bodyStyle={{ padding: '5px 2px' }}
      title={
        <>
          <AutoComplete
            style={{ width: '100%' }}
            options={autoCompleteOptions}
            notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            onSelect={onAutoSelectLeft}
          >
            <Input placeholder="请按物料类型搜索" suffix={<SearchOutlined />} onChange={onInputChange} value={typeTreeSearchObj?.searchValue || ''} />
          </AutoComplete>
        </>
      }
    >
      <Spin spinning={mapLoading}>
        <ScrollBarLayout style={{ margin: '0 10px' }}>
          {materialTypeMapList?.length === 0 ? (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
          ) : (
            <Tree
              onSelect={onSelectTree}
              blockNode={true}
              onCheck={onCheck}
              treeData={orgTreeData(materialTypeMapList)}
              selectedKeys={selectKeys}
              expandedKeys={typeTreeSearchObj?.expandedKeys}
              defaultExpandParent={true}
              onExpand={onTreeExpand}
            />
          )}
        </ScrollBarLayout>
      </Spin>
    </Card>
  );
};
